<?php

	// Edits to a domain's name may only be made by editing the config file.
	// This class only accepts commital when called by the DesktopDomain class

	final class SmRoot0v0r01_Domain extends _smuoiDbRow implements SmRoot_Domain{
		
		protected $table = 'domains';
		
		private $update_deskdir_perms;
		private $DOMAIN;
		
		protected $get_functions = 'dom_id';
		protected $set_functions = 'own,grp,name';
			
		protected $dom_commit_called = false;
			
		function dom_id(){
			return $this->pkg->remove_key($this->id);
		}
		
		function DOMAIN(){
			if(is_null($this->DOMAIN)) $this->DOMAIN = Domain($this->dom_id());
			return $this->DOMAIN;
		}
				
		protected function set_own($o){
			if(!$o instanceof SmRoot_User) return false;
			return $this->edits['own'] = $o->id;
		}
		
		protected function set_grp($o){
			if(!$o instanceof SmRoot_group) return false;
			return $this->edits['grp'] = $o->id;
		}
		
		protected function set_name($n){
			return $this->hard_set('name', $n);
		}
		
		// Commit should only be called by the Domain() object
		function dom_commit(){
			$this->dom_commit_called = true;
			return $this->commit(1);
		}
		
		protected function prepare_commit(){
			if(!$this->dom_commit_called){
				$this->DOMAIN()->commit();
				return false;
			}
			return parent::prepare_commit();
		}

		protected function run_sanity_checks(){
			if($this->is_edited('own') || $this->is_edited('grp')) $this->update_deskdir_perms = true;	
		}
		
		protected function post_commit(){
			$this->dom_commit_called = false;
			if($this->update_deskdir_perms){
				if(!$Desk = $this->DOMAIN()->Desk()) return;	
				if($Desk->own !== $this->data->own) $Desk->own = smdb($this->data->own);
				if($Desk->grp !== $this->data->grp) $Desk->grp = smdb($this->data->grp);
				$Desk->commit(1);
				$this->update_deskdir_perms = false;
			}
		}
		
		// All domains have mode effective mode 770 in the DSK context since their permissions are a replica of the the Desk() object.
		function will_permit($usr){
			switch(true){
				case (!$usr): return false;
				case ($usr instanceof SmRoot_Root): return true;
				case ($usr->id == $this->data->own): return true;
				case (in_array($this->data->grp, $usr->groups())): return true;
			}
			return false;
		}
	}

?>